package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.Exception.toTshowException;
import com.dongdongshop.domain.DataResult;
import com.dongdongshop.em.DataResultEnum;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.TbSellerService;
import com.dongdongshop.utils.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/*商家后台*/
@RequestMapping("LoginController")
@Controller
public class LoginController {

    @Reference
    private TbSellerService tbSellerService;

    @RequestMapping("ToLogin")
    public String ToLogin(){
        return "register";
    }
    @RequestMapping("shoplogin")
    public String toshoplogin(){
        return "shoplogin";
    }
    /*注册*/
    @RequestMapping("toadd")
    @ResponseBody
    public DataResult toadd(TbSeller tbSeller){
        try {
            String salt = ShiroUtils.generateSalt(5);
            tbSeller.setYan(salt);
            tbSeller.setYancount(3);
            String md5 = ShiroUtils.encryptPassword("MD5", tbSeller.getPassword(), salt, 5);
            tbSeller.setPassword(md5);
            tbSeller.setCreateTime(new Date());
            tbSellerService.tbSellerService(tbSeller);
            return  DataResult.buildDataResult(DataResultEnum.SUCCESS);
        }catch (Exception e){
            return  DataResult.buildDataResult(DataResultEnum.ERROR);
        }
    }

    /*登陆*/
    @RequestMapping("toTshow")
    @ResponseBody
    public DataResult toTshow(String sellerId,String password){
        Subject subject = SecurityUtils.getSubject();
        /*分装token令牌*/
        UsernamePasswordToken token = new UsernamePasswordToken(sellerId,password);
        try {
            subject.login(token);
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            e.printStackTrace();
            return DataResult.buildDataResult(DataResultEnum.ERROR).setData("账号或密码错误");
        }catch (toTshowException e){
            return DataResult.buildDataResult(DataResultEnum.ERROR).setData(e.getMessage());
        }
        return  DataResult.buildDataResult(DataResultEnum.SUCCESS);
    }

    @RequestMapping("index")
    public String toshoplogins(){
        return "/admin/index";
    }
}
